import { Matrix4} from '../../../core/math/index';
import { FeatureTable, BatchTable } from './FeatureTable';
import { loadGLTFObject } from "../../gltf/gltfParse"
import { GltfObject } from './GltfObject';

const zUpToYUpMatrix = new Matrix4();
zUpToYUpMatrix.set(
	1, 0, 0, 0,
	0, 0, -1, 0,
	0, 1, 0, 0,
	0, 0, 0, 1);

export class B3DMDecoder {
	constructor() {
		
		this.gltfLoader = {};
		this.tempMatrix = new Matrix4();

		
	}

	parseB3DM(arrayBuffer, meshCallback, sceneZupToYUp, meshZUpToYUp,path,tile) {
		const dataView = new DataView(arrayBuffer);

		const magic =
			String.fromCharCode(dataView.getUint8(0)) +
			String.fromCharCode(dataView.getUint8(1)) +
			String.fromCharCode(dataView.getUint8(2)) +
			String.fromCharCode(dataView.getUint8(3));
		console.assert(magic === 'b3dm');

		const byteLength = dataView.getUint32(8, true);
		console.assert(byteLength === arrayBuffer.byteLength);

		const featureTableJSONByteLength = dataView.getUint32(12, true);
		const featureTableBinaryByteLength = dataView.getUint32(16, true);
		const batchTableJSONByteLength = dataView.getUint32(20, true);
		const batchTableBinaryByteLength = dataView.getUint32(24, true);

		const featureTableStart = 28;
		const featureTable = new FeatureTable(arrayBuffer, featureTableStart, featureTableJSONByteLength, featureTableBinaryByteLength);

		const batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
		const batchTable = new BatchTable(arrayBuffer, featureTable.getData('BATCH_LENGTH'), batchTableStart, batchTableJSONByteLength, batchTableBinaryByteLength);

		const glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
		const glbBytes = new Uint8Array(arrayBuffer, glbStart, byteLength - glbStart);


		const gltfBuffer = glbBytes.slice().buffer;


		return new Promise(async (resolve, reject) => {
			const jsonLength = new Uint32Array(gltfBuffer, 12, 1)[0];
			const jsonChunk = new Uint8Array(gltfBuffer, 20, jsonLength);
			const json = JSON.parse(new TextDecoder("utf-8").decode(jsonChunk));
			const gltfObject = await loadGLTFObject(json, path, gltfBuffer, 28 + jsonLength);
			const objectGlb= new GltfObject(gltfObject,tile)
			// console.log(gltfObject,"gltfObject");
			const rtcCenter = featureTable.getData('RTC_CENTER');

			resolve(objectGlb.node);
			// if (rtcCenter) {
			// 	this.tempMatrix.makeTranslation(rtcCenter[0], rtcCenter[1], rtcCenter[2])
			// 	// model.scene.applyMatrix4(this.tempMatrix);
			// } else if (!!model.userData.gltfExtensions && !!model.userData.gltfExtensions.CESIUM_RTC) {
			// 	this.tempMatrix.makeTranslation(model.userData.gltfExtensions.CESIUM_RTC.center[0], model.userData.gltfExtensions.CESIUM_RTC.center[1], model.userData.gltfExtensions.CESIUM_RTC.center[2])
			// 	// model.scene.applyMatrix4(this.tempMatrix);
			// }
     
		});
	}


}

